package com.sec.android.app.myfiles.facade.cmd;

import android.app.Activity;
import android.content.Context;

import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperator.Operation;
import com.sec.android.app.myfiles.util.FileUtils;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import java.util.ArrayList;

public class ImportFromAppsCmd extends SimpleCommand {

    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();

        AbsMyFilesFragment fragment = (AbsMyFilesFragment) params[0];

        int processId = fragment.getProcessId();
        ArrayList<FileRecord> srcRecordList = fragment.getSelectedFile();
        Activity activity = fragment.getActivity();
        Context context = activity.getApplicationContext();

        NavigationManager navigationManager = NavigationManager.getInstance(processId);

        NavigationInfo preInfo = navigationManager.getCurInfo();
        if (preInfo != null) {
            navigationManager.goToRestoreNavigationStack(preInfo);
        }

        boolean valid = checkFilesValid(context, srcRecordList);
        NavigationInfo curInfo = navigationManager.getCurInfo();
        if (valid && curInfo != null) {
            MyFilesFacade.copymoveRecord(processId, context, Operation.MOVE, CopyMoveCmd.OperationProgress.DO_OPERATE, fragment,
                    srcRecordList, curInfo.getCurRecord());
        }
    }

    private boolean checkFilesValid(Context context, ArrayList<FileRecord> records) {
        boolean bRet = true;

        if (records != null && !records.isEmpty()) {
            for (FileRecord record : records) {
                if (!FileUtils.isValidFile(context, record)) {
                    bRet = false;
                    break;
                }
            }
        } else {
            bRet = false;
        }
        return bRet;
    }
}
